------------------------------------------------------------------------------------------------------------------------------------------------
-- -- tasks base lib
local function language_change_say(theNPC)
    theNPC.CHAT_TABLE = {}
    pcall(function()
        -- theNPC.npc_base_lib:Get_Language() == "ch"
        theNPC.CHAT_TABLE = TUNING.NPC_CHAT_TABLE[ theNPC.npc_base_lib:Get_Language() ] ["npc_event_wolfgang_and_horn"] or {}
    end)
end

-------------------------------------------------------------------------------------------------------------------------------------------------


local function horn_action_end_fn(theNPC)
    ------ 召唤完怪物后，去到 theNPC.__horn_waiting_step
    theNPC.__monsters = {}
    local theplayer = theNPC:GetPlayer()
    local points = theNPC.npc_base_lib:GetSurroundPoints({
        target = theplayer,
        range = 6.5,
        num = 6
    })
    local MonsterNames = {"hound","spider","mutatedhound","knight","tallbird","pigguard"}
    local ret_name = theNPC.npc_base_lib:GetRandom(MonsterNames)
    for k, pt in pairs(points) do
        local monster = SpawnPrefab(ret_name)
        monster:AddTag("npc_task")  --- 不给守卫打掉
        monster.Transform:SetPosition(pt.x,0,pt.z)
        -- monster.components.health:SetPercent(0.3)
        monster.components.health.currenthealth = 20
        monster.components.combat:SetTarget(theplayer)
        theNPC.__monsters[monster] = true
        SpawnPrefab("npc_fx_spawn"):PushEvent("Set",{
            pt = pt,
            no_sound = true,
        })
        monster:DoPeriodicTask(0.5,function()
            if theplayer:IsValid() then
                if theplayer:HasTag("playerghost") then
                    monster.components.health:Kill()
                else
                    monster.components.combat:SetTarget(theplayer)  
                end        
            else
                monster:Remove()
            end
        end)
    end
    theNPC.event_step = theNPC.__horn_waiting_step

end

local function horn_waiting_next_check(theNPC)
    if theNPC.__monsters == nil then
        theNPC.event_step = theNPC.__horn_start_step
        return true
    end

    -------------------------------------------------------------------
    --- 在这一步检查玩家发生意外
    local theplayer = theNPC:GetPlayer()
    if theplayer:HasTag("playerghost") then
        theNPC.event_step = theNPC.__horn_player_die_step
        return true
    end
    -------------------------------------------------------------------
    for monster , v in pairs(theNPC.__monsters) do  --- 如果还有怪物存在，不去下一步，保持 在这一步
        if monster:IsValid() then
            return false
        end
    end

    if theNPC.npc_everything_data:Add("TASK_NUM",1) < 5 then
        theNPC.event_step = theNPC.__horn_start_step
        return true
    else
        theNPC.event_step = theNPC.__horn_final_step
        return true
    end
end



local function player_die_task(theNPC)
    local theplayer = theNPC:GetPlayer()
    theplayer:PushEvent("respawnfromghost",{ source = theNPC })
    theNPC.event_step = theNPC.__horn_final_step
end

-------------------------------------------------------------------------------------------------------------------------------------------------
local function Time_Out_Leave(inst)
    local theNPC = inst.entity:GetParent()
    local time = theNPC.npc_base_lib:Get_Time_Out()
    if time then
        inst:DoTaskInTime(time,function()
            inst:Remove()
            theNPC:AddDebuff("npc_event_leave","npc_event_leave")
            theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.time_out)
            print("Warning : npc time out and leave")
        end)
    end
end


local function NPC_TASKS_INIT(inst)
    local theNPC = inst.entity:GetParent()
    language_change_say(theNPC)
    Time_Out_Leave(inst)
    
    theNPC.npc_base_lib:Equip_Random_Hat()
    theNPC.npc_base_lib:Equip_Random_Cloth()
    -- theNPC.npc_base_lib:Equip_Random_Weapon()
    theNPC:AddTag("INLIMBO")
    theNPC:AddTag("notarget")
    theNPC:AddTag("noattack")
    theNPC:AddTag("invisible")
    -- theNPC:AddTag("Unable_To_Refuse")
    theNPC.npc_event = inst.prefab
end

local function NPC_TASKS(inst)
    local theNPC = inst.entity:GetParent()
    -- print("Step:",theNPC.event_step)
    if TheWorld.state.isnight  or TheWorld:HasTag("cave") then
        theNPC.npc_base_lib:Try_2_Set_Light(true)
    else
        theNPC.npc_base_lib:Try_2_Set_Light(false)
    end
    local theplayer = theNPC.__link_player
    if theplayer == nil or theplayer:IsValid() == false then
        -- theNPC:RemoveDebuff(inst.prefab)
        inst:Remove()
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
        print("Warning : theNPC.__link_player == nil")
        return
    end

    if theNPC.event_step == nil then

        if theNPC.npc_base_lib:Close_2_Target_In_Range({range = 5}) == true then
            theNPC.event_step = 1
        end
        
    elseif theNPC.event_step == 1 then

        theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.warm_up_exercise)
        theNPC.event_step = theNPC.event_step + 1

    elseif theNPC.event_step == 2 then
        if theNPC.npc_everything_data:Add("wait.001",1) % 3 == 0 then
            theNPC.event_step = theNPC.event_step + 1
        end
    -----------------------------------------------------------------------------------------------------------------------------------
    elseif theNPC.event_step == 3 then
        theNPC.__horn_start_step = 3
        theNPC.__horn_ation_step = 4
        theNPC.__horn_waiting_step =5
        theNPC.__horn_final_step = 9
        theNPC.__horn_player_die_step = 6
        -- 开始 step
        if theNPC.npc_base_lib:Run_Around_Target_In_Range({range = 6,random_range_flag = true , mid_reflash_range = 3}) then
            theNPC.event_step = 4
        end        
    elseif theNPC.event_step == 4 then
        -- 召唤 step
        theNPC.last_step = 3
        theNPC.npc_base_lib:Action_Horn(horn_action_end_fn)
    elseif theNPC.event_step == 5 then
        ---- 等待 step
        if horn_waiting_next_check(theNPC) == false then        
            theNPC.npc_base_lib:Run_Around_Target_In_Range({range = 6,random_range_flag = true , mid_reflash_range = 3})
        end
-----------------------------------------------------------------------------------------------------------------------------------
    elseif theNPC.event_step == 6 then
        --- 复活玩家
        theNPC.npc_base_lib:Action_Horn(player_die_task)

    elseif theNPC.event_step == 9 then
        if theNPC.npc_everything_data:Add("wait.002",1) % 5 == 0 then
            theNPC.event_step = 10
        end
    elseif theNPC.event_step == 10 then
        -- theNPC.event_step = theNPC.event_step + 1
        -- theNPC:RemoveDebuff(inst.prefab)
        inst:Remove()
        theNPC.npc_base_lib:Say("Bye ~ ")
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
    end
end
--------------------------------------------------------------------------------------------------------------------------------------------------

local function OnAttached(inst,target) -- when the debuff on or player is newSpawn(or through the cave)
    inst.entity:SetParent(target.entity)
    inst.Network:SetClassifiedTarget(target)
    local NPC = inst.entity:GetParent()
    local flag ,error_code= pcall(function(inst,target)
        if TheWorld.ismastersim then

            NPC_TASKS_INIT(inst)


        end
    end,inst,target)
    if flag == false  then
        print("Error : OnAttached(inst,target) ",inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function OnDetached(inst) -- When eliminating from the outside
    local player = inst.entity:GetParent()   
    -- print(" FROM OUSIDE REMOVE ")
    
    -- inst:Remove()
end

local function ExtendDebuff(inst)
    -- inst.countdown = 3 + (inst._level:value() < CONTROL_LEVEL and EXTEND_TICKS or math.floor(TUNING.STALKER_MINDCONTROL_DURATION / FRAMES + .5))
end



local function OnUpdate(inst,ismastersim)
    local NPC = inst.entity:GetParent()
    local flag,error_code = pcall(function(inst,ismastersim)
        -- local NPC = inst.entity:GetParent()

        NPC_TASKS(inst)


    end,inst,ismastersim)
    if flag == false then
        print("Error : OnUpdate(inst,ismastersim) ,step:",NPC.event_step ,inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddNetwork()

    inst:AddTag("CLASSIFIED")


    -- inst:DoPeriodicTask(1, OnUpdate, nil, TheWorld.ismastersim)  -- in one seconds
    inst:DoPeriodicTask( 0.5, OnUpdate, nil, TheWorld.ismastersim)  -- in 0.5 seconds

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("debuff")
    inst.components.debuff:SetAttachedFn(OnAttached)
    inst.components.debuff.keepondespawn = false -- 是否保持debuff 到下次登陆
    -- inst.components.debuff:SetDetachedFn(inst.Remove)
    inst.components.debuff:SetDetachedFn(OnDetached)
    -- inst.components.debuff:SetExtendedFn(ExtendDebuff)
    -- ExtendDebuff(inst)


    return inst
end

return Prefab("npc_event_wolfgang_and_horn", fn)
